package cn.cdzdjd.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.json.JSONObject;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.constant.LocationRedirect;
import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.IXiGuaService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class IXiGuaServiceImpl implements IXiGuaService {
	private final String baseUrl = "http://47.99.158.118/video-crack/v2/parse?content=";
	private final String getTtwid = "https://ttwid.bytedance.com/ttwid/union/register/";
	private final String body = "{\"region\":\"cn\",\"aid\":1768,\"needFid\":false,\"service\":\"www.ixigua.com\",\"cbUrlProtocol\":\"https\",\"union\":true,\"fid\":\"\"}";

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		try {

			// 重要步骤，必须先获取到ttwid,否则进入不了视频页面
			Response ttwidRes = Jsoup.connect(getTtwid).ignoreContentType(true).ignoreHttpErrors(true)
					.userAgent(BrowserConstant.USER_AGENT_PC).header("Accept", BrowserConstant.ACCEPT).requestBody(body)
					.method(Method.POST).referrer(url).execute();
			Map<String, String> ttwidCooike = ttwidRes.cookies();
			String locationUrl1 = LocationRedirect.getLocationPC(url);
			String locationUrl2 = LocationRedirect.getLocationPC(locationUrl1);
			Response response = JsoupUtil.getUrlResponse(locationUrl2);
			Map<String, String> tokenCookies = response.cookies();
			tokenCookies.putAll(ttwidCooike);
			Document document = JsoupUtil.getDocumentCookie(response.url().toString(), tokenCookies);
			String ssr_data = document.selectFirst("script[id=SSR_HYDRATED_DATA]").data();
			int index = StringUtils.ordinalIndexOf(ssr_data, "{", 1);
			String jsonStr = StringUtils.substring(ssr_data, index);
			JSONObject json = new JSONObject(jsonStr.replaceAll("undefined", "null"));
			JSONObject video = json.getJSONObject("anyVideo").getJSONObject("gidInformation")
					.getJSONObject("packerData").getJSONObject("video");
			String videoTitle = video.getString("title");
			String poster_url = StringEscapeUtils.unescapeJava(video.getString("poster_url"));
			Response videoRes = JsoupUtil.getUrlResponse(baseUrl + locationUrl2);
			String videoStr = videoRes.body();
			JSONObject videoJson = new JSONObject(videoStr);
			String videoUrl = videoJson.getJSONObject("data").getString("url");
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(poster_url));
			return new VideoInfoVO(videoList, posterList, videoTitle, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RenException(ErrorCode.PARSE_ERROR);
		}
	}
}
